package com.soujiayi.search;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

public class SearchSuggestion {

	public static List<String> getSuggestion(String text)
			throws ClientProtocolException, IOException, Exception {
		List<String> result = new ArrayList<String>();

		//
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		try {

			HttpClient httpget = new DefaultHttpClient();
			HttpGet request = new HttpGet(
					"http://google.com/complete/search?output=toolbar&q="
							+ URLEncoder.encode(text).replace("%EF%BB%BF", "")
							+ "&hl=zh-CN");

			request.setHeader("charset", "utf-8");

			ResponseHandler<String> rh = new BasicResponseHandler();
			String response = httpget.execute(request, rh);

			InputStream is = new ByteArrayInputStream(
					response.getBytes("UTF-8"));

			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom;
			dom = builder.parse(is);

			org.w3c.dom.Element root = dom.getDocumentElement();
			// Log.e("XML", root.toString());
			NodeList items = root.getElementsByTagName("suggestion");

			for (int i = 0; i < items.getLength(); i++) {
				Element element = (Element) items.item(i);
				result.add(element.getAttribute("data").toString());

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("unused")
	private static String convertStreamToString(InputStream is) {

		Charset ch = Charset.forName("UTF8");
		Log.i("ccc", "CHARSET=" + ch.displayName());

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(is, ch));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		String originalStr = new String(sb.toString());

		return sb.toString();
	}

	public static Document parse(String xml) {
		Document doc = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			// encode the xml to UTF -8

			ByteArrayInputStream encXML = new ByteArrayInputStream(
					xml.getBytes("UTF8"));

			doc = builder.parse(encXML);
			// Log.e("XML parsing OK");

			return doc;
		} catch (Exception e) {
			// log.error("Parser Error:" + e.getMessage());
			// throw new ParsingFailedException(
			// "Failed to parse XML : Document not well formed", e);
		}
		return doc;
	}
}
